import React, { useState, useEffect } from 'react';
import { Form, Input, Button, Tabs, message, Card } from 'antd';
import { UserOutlined, LockOutlined, MobileOutlined, SafetyOutlined } from '@ant-design/icons';
import { useNavigate } from 'react-router-dom';
// 修改 CSS 导入路径
import 'antd/dist/reset.css'; // 对于 Ant Design v5+

const { TabPane } = Tabs;
const [messageApi, contextHolder] = message.useMessage(); // 使用 message 的 hooks API

const Login = () => {
  const [loginType, setLoginType] = useState('password');
  const [countdown, setCountdown] = useState(0);
  const [background, setBackground] = useState('linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%)');
  const [form] = Form.useForm();
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();

  // 生成随机淡色
  const getRandomPastelColor = () => {
    const hue = Math.floor(Math.random() * 360);
    const saturation = Math.floor(Math.random() * 30) + 70; // 70-100%
    const lightness = Math.floor(Math.random() * 20) + 70; // 70-90%
    return `hsl(${hue}, ${saturation}%, ${lightness}%)`;
  };

  // 生成随机渐变背景
  const getRandomGradient = () => {
    const color1 = getRandomPastelColor();
    const color2 = getRandomPastelColor();
    const angle = Math.floor(Math.random() * 360);
    return `linear-gradient(${angle}deg, ${color1} 0%, ${color2} 100%)`;
  };

  // 每3秒更换背景
  useEffect(() => {
    const intervalId = setInterval(() => {
      setBackground(getRandomGradient());
    }, 3000);

    return () => clearInterval(intervalId);
  }, []);

  const handleLogin = async (values) => {
    setLoading(true);
    
    try {
      if (loginType === 'password') {
        // 账号密码登录
        const response = await fetch('http://localhost:3001/api/login', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json',
          },
          body: JSON.stringify({
            username: values.username,
            password: values.password
          }),
        });
        
        const result = await response.json();
        
        if (result.code === 200) {
          // 登录成功，保存token和用户信息
          localStorage.setItem('token', result.data.token);
          localStorage.setItem('userInfo', JSON.stringify(result.data.user));
          messageApi.success('登录成功'); // 使用 messageApi 替代 message
          navigate('/dashboard');
        } else {
          // 登录失败
          messageApi.error(result.message || '用户名或密码错误'); // 使用 messageApi 替代 message
        }
      } else {
        // 手机验证码登录 - 这里可以添加实际的手机验证码登录接口
        // 目前仍使用模拟数据
        if (values.phone === '18888888888' && values.verificationCode === '123456') {
          localStorage.setItem('token', 'demo-token');
          message.success('登录成功');
          navigate('/dashboard');
        } else {
          message.error('手机号或验证码错误！默认手机号：18888888888，验证码：123456');
        }
      }
    } catch (error) {
      console.error('登录请求失败:', error);
      messageApi.error('登录失败，请检查网络连接'); // 使用 messageApi 替代 message
    } finally {
      setLoading(false);
    }
  };

  const handleSendCode = () => {
    form.validateFields(['phone']).then(values => {
      if (values.phone && values.phone.length === 11) {
        message.success('验证码发送成功，请查收');
        setCountdown(60);
        const timer = setInterval(() => {
          setCountdown(prevCount => {
            if (prevCount <= 1) {
              clearInterval(timer);
              return 0;
            }
            return prevCount - 1;
          });
        }, 1000);
      }
    }).catch(() => {
      message.error('请输入正确的手机号码');
    });
  };

  return (
    <div style={{ 
      minHeight: '100vh',
      display: 'flex',
      justifyContent: 'center',
      alignItems: 'center',
      background: background,
      transition: 'background 1.5s ease',
      padding: '20px'
    }}>
      {contextHolder} {/* 在组件顶层添加 contextHolder */}
      <Card 
        style={{ 
          width: 400, 
          borderRadius: '8px',
          boxShadow: '0 4px 12px rgba(0, 0, 0, 0.1)',
          background: 'rgba(255, 255, 255, 0.9)'
        }}
      >
        <h1 style={{ textAlign: 'center', marginBottom: '24px' }}>系统登录</h1>
        
        <Tabs 
          activeKey={loginType} 
          onChange={setLoginType}
          centered
        >
          <TabPane tab="账号密码登录" key="password">
            <Form
              form={form}
              name="password_login"
              onFinish={handleLogin}
              initialValues={{ username: 'admin', password: '123456' }}
            >
              <Form.Item
                name="username"
                rules={[{ required: true, message: '请输入用户名!' }]}
              >
                <Input 
                  prefix={<UserOutlined />} 
                  placeholder="用户名 (默认: admin)" 
                  size="large"
                />
              </Form.Item>
              <Form.Item
                name="password"
                rules={[{ required: true, message: '请输入密码!' }]}
              >
                <Input.Password 
                  prefix={<LockOutlined />} 
                  placeholder="密码 (默认: 123456)" 
                  size="large"
                />
              </Form.Item>
              <Form.Item>
                <Button type="primary" htmlType="submit" block size="large" loading={loading}>
                  登录
                </Button>
              </Form.Item>
            </Form>
          </TabPane>
          
          {/* 手机验证码登录部分保持不变 */}
        </Tabs>
        
        <div style={{ textAlign: 'center', fontSize: '12px', color: '#666', marginTop: '16px' }}>
          <p>默认账号: admin / 密码: 123456</p>
          <p>默认手机号: 18888888888 / 验证码: 123456</p>
        </div>
      </Card>
    </div>
  );
};

export default Login;